package com.negative.activities;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import com.negative.logic.TokenExtractor;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

@SuppressLint("SetJavaScriptEnabled")
public class PurchaseActivity extends Activity{

	TextView title;
	WebView webView;

	String eventName;
	long eventID;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_purchase);

		title = (TextView) findViewById(R.id.event_page_date_label);
		webView = (WebView) findViewById(R.id.webView1);

		eventName = this.getIntent().getStringExtra("Name");
		eventID = this.getIntent().getLongExtra("ID", 0);
		String encodedEventName = "";
		try {
			encodedEventName = URLEncoder.encode(eventName,"UTF-8");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		final String html = getResources().getString(R.string.url_event_page) + eventID + "/" + encodedEventName ; 
		TokenExtractor extractor = new TokenExtractor(html, eventID);
		extractor.start();
		while(!extractor.isFinished());
		String token = extractor.getToken();
		Log.i("outside", token);
		String url = createUrlWithToken(token);
		String iframeUrl = addIframeFromUrl(url);
		title.setText(Html.fromHtml(eventName));
		updateView(iframeUrl);
	}

	private String createUrlWithToken(String token) {
		String url = "https://www.tixwise.co.il/he/event/"+
				eventID+"/"+
				token+
				"?widget%5Bwidget%5D=1&widget%5Bt_theme%5D=yellow&" +
				"widget%5Bb_theme%5D=light_blue1&widget%5Breffering_url%5D=" +
				"http%3A%2F%2Fwww.bgu4u.co.il%2Fsite.aspx%3FSiteId%3D8&widget%5Btarget%5D=top\" " +
				"scrolling=\"no\" frameborder=\"0\" allowTransparency=\"true\" style=\"border:none; " +
				"overflow:hidden; width:300; height:350;\"";
		return url;
	}

	private void updateView(String url) {
		webView.getSettings().setJavaScriptEnabled(true);		
		webView.setWebViewClient(new WebViewClient());
		webView.loadData(url, "text/html", null);

		
	}

	private String addIframeFromUrl(String url) {

		return "<iframe src="+url+"></iframe>";
	}

	@Override
	public void onBackPressed() {
		if (webView.canGoBack())
			webView.goBack();
		else
			super.onBackPressed();
	}
}